package com.dragonboat.service;
import com.dragonboat.util.PasswordUtil;
import com.dragonboat.entity.Event;
import com.dragonboat.entity.Organizer;
import com.dragonboat.entity.Registration;
import com.dragonboat.entity.Team;
import com.dragonboat.repository.EventRepository;
import com.dragonboat.repository.OrganizerRepository;
import com.dragonboat.repository.RegistrationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class OrganizerService {
    @Autowired
    private OrganizerRepository organizerRepository;

    @Autowired
    private EventRepository eventRepository;

    @Autowired
    private RegistrationRepository registrationRepository;

    public Optional<Organizer> login(Integer organizerId, String password) {
        return organizerRepository.findById(organizerId)
                .filter(o -> PasswordUtil.matches(password, o.getPassword()));
    }
    public Optional<Organizer> loginByName(String organizerName, String password) {
        return organizerRepository.findByOrganizerName(organizerName)
                .filter(o -> PasswordUtil.matches(password, o.getPassword()));
    }
    public Organizer getOrganizerById(Integer organizerId) {
        return organizerRepository.findById(organizerId).orElse(null);
    }

    public Event publishEvent(Event event) {

        event.setStatus("upcoming");
        return eventRepository.save(event);
    }

// OrganizerService.java 添加以下内容

    public List<Registration> getRegistrationsByOrganizer(Integer organizerId) {
        return registrationRepository.findByEventOrganizerOrganizerId(organizerId);
    }

    public Registration updateRegistrationStatus(Integer registrationId, String status) {
        return registrationRepository.findById(registrationId)
                .map(registration -> {
                    registration.setStatus(status);
                    return registrationRepository.save(registration);
                })
                .orElseThrow(() -> new RuntimeException("Registration not found"));
    }



    public Organizer updateOrganizerInfo(Integer organizerId, String name, String newPassword) {
        return organizerRepository.findById(organizerId).map(organizer -> {
            if (name != null && !name.isEmpty()) organizer.setOrganizerName(name);
            if (newPassword != null && !newPassword.isEmpty()) organizer.setPassword(newPassword);
            return organizerRepository.save(organizer);
        }).orElse(null);
    }

}